import cv2
import numpy as np


def find_corners_of_image(image_path):
    # 读取图像
    image = cv2.imread(image_path)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 二值化处理
    _, thresh = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY)  # 假设黑色区域的像素值接近0

    # 寻找轮廓
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 筛选矩形轮廓
    for cnt in contours:
        # 近似轮廓
        epsilon = 0.1 * cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, epsilon, True)

        # 如果轮廓有4个顶点，则认为是矩形
        if len(approx) == 4:
            # 获取角点坐标
            corners = approx.reshape(4, 2)
            return corners

    return None


# 调用函数并打印结果
image_path = r'E:\datasets\sat_geo_loc_test\test_image\5.TIF'  # 替换为你的图像路径
corners = find_corners_of_image(image_path)
if corners is not None:
    print("四个角点的像素坐标:")
    print(corners)
else:
    print("未找到合适的矩形轮廓")
